package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.UserAddressDao;
import com.leoman.dao.UserDao;
import com.leoman.entity.Region;
import com.leoman.entity.User;
import com.leoman.entity.UserAddress;
import com.leoman.exception.AddressNotFindException;
import com.leoman.exception.ParamErrorException;
import com.leoman.exception.UserNotFindException;
import com.leoman.exception.UserSealStatusException;
import com.leoman.service.UserAddressService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * UserAddressServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:01.
 */
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserAddressDao userAddressDao;

    @Autowired
    private UserDao userDao;

    @Override
    public List<UserAddress> findAll() {
        return userAddressDao.findAll();
    }

    @Override
    public Page<UserAddress> find(int pageNum, int pageSize) {
        return userAddressDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<UserAddress> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public UserAddress getById(int id) {
        return userAddressDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        userAddressDao.delete(id);
    }

    @Override
    public UserAddress create(UserAddress userAddress) {
        return userAddressDao.save(userAddress);
    }

    @Override
    public UserAddress update(UserAddress userAddress) {
        return userAddressDao.save(userAddress);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<UserAddress> iPageByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        Page<UserAddress> page = userAddressDao.iPageByUserId(userId, new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isDefault", "id"));

        for (UserAddress userAddress : page.getContent()) {
            userAddress.setRegionId(userAddress.getRegion().getId());
            userAddress.setRegionInfo(userAddress.getRegion().getCity().getProvince().getName() + "-" + userAddress.getRegion().getCity().getName() + "-" + userAddress.getRegion().getName());
        }

        return page;
    }

    @Override
    @Transactional
    public void iAddAddressInfo(Integer userId, Integer addressId, String userName, String mobile, Integer regionId, String description, Integer isDefault) throws ParamErrorException, UserNotFindException, UserSealStatusException {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(mobile) || null == regionId || StringUtils.isBlank(description)) {
            throw new ParamErrorException();
        }

        if (null == isDefault) {
            isDefault = Constant.USER_STATUS_NO;
        }

        User user = UserServiceImpl.getUserInfo(userId, userDao);
        UserAddress userAddress;

        // 查询默认收货地址
        UserAddress defaultAddress = userAddressDao.findOneWithUserIdAndDefault(userId);

        if (null == addressId) {
            userAddress = new UserAddress();

            if (null == defaultAddress) {
                userAddress.setIsDefault(Constant.USER_STATUS_YES);
            }
        } else {
            userAddress = userAddressDao.findOne(addressId);
            userAddress.setUpdateTime(System.currentTimeMillis());
        }

        if (isDefault.equals(Constant.USER_STATUS_YES)) {
            if (null != defaultAddress) {
                defaultAddress.setIsDefault(Constant.USER_STATUS_NO);
                defaultAddress.setUpdateTime(System.currentTimeMillis());

                userAddressDao.save(defaultAddress);
            }

            userAddress.setIsDefault(Constant.USER_STATUS_YES);
        }

        Region region = new Region();
        region.setId(regionId);

        userAddress.setUser(user);
        userAddress.setUserName(userName);
        userAddress.setMobile(mobile);
        userAddress.setRegion(region);
        userAddress.setDescription(description);

        userAddressDao.save(userAddress);
    }

    @Override
    public void iDeleteAddressInfo(Integer addressId) throws ParamErrorException, AddressNotFindException {
        if (null == addressId) {
            throw new ParamErrorException();
        }

        UserAddress userAddress = userAddressDao.findOne(addressId);

        if (null == userAddress) {
            throw new AddressNotFindException();
        }

        User user = userAddress.getUser();

        deleteById(userAddress.getId());

        if (null == userAddressDao.findOneWithUserIdAndDefault(user.getId())) {
            // 如果没有默认收获地址，将第一个收获地址设置为默认地址
            List<UserAddress> list = userAddressDao.findListByUserId(user.getId());

            if (list.size() > 0) {
                UserAddress tempAddress = list.get(0);
                tempAddress.setIsDefault(Constant.USER_STATUS_YES);
                tempAddress.setUpdateTime(System.currentTimeMillis());
                userAddressDao.save(tempAddress);
            }
        }
    }

    @Override
    public List<UserAddress> findListByUserId(Integer userId) {
        return userAddressDao.findListByUserId(userId);
    }

    @Override
    public UserAddress findDefaultByUserId(Integer userId) {
        UserAddress userAddress = userAddressDao.findOneWithUserIdAndDefault(userId);

        if (null != userAddress && null != userAddress.getRegion()) {
            userAddress.setRegionId(userAddress.getRegion().getId());
            userAddress.setRegionInfo(userAddress.getRegion().getCity().getProvince().getName() + "-" + userAddress.getRegion().getCity().getName() + "-" + userAddress.getRegion().getName());
        }

        return userAddress;
    }
}